package com.yami.shop.api.utils;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;

public class ApacheHttp {
    private static Logger logger = LoggerFactory.getLogger(ApacheHttp.class);

    public static String getNewFileName(String dir)  {
        try {
            //以上期为子目录，是否存在
            String subDir = HttpClient.getYYYYMMDD();
            File f = new File(dir + subDir);
            if (f.exists()) {

            } else {
                f.mkdirs();
            }
            String fileName = dir + subDir + "/" + HttpClient.getRandomFileName();

            return fileName;
        }catch (Exception e){
            return "";
        }
    }

    //下载图片到指定目录，生成随机文件名
    public static String downloadToDir(String url,String dir) throws Exception {
        //以上期为子目录，是否存在
        String subDir=HttpClient.getYYYYMMDD();
        File f=new File(dir+subDir);
        if(f.exists()){

        }else{
            f.mkdirs();
        }
        String fileName=dir+subDir+"/"+HttpClient.getRandomFileName();
        fileName=getFile(url,fileName);
        return  fileName;
    }


    public static String get(String url) {
        logger.info("apache http get:"+url);
        CloseableHttpClient client=null;
        HttpResponse response=null;
        try {
            client = HttpClientBuilder.create().build();
            HttpGet request = new HttpGet(url);


            response = client.execute(request);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String ret=EntityUtils.toString(entity,"utf-8");
                logger.info(ret);
                return ret;
            }
            return  null;
        }catch (Exception e){
            e.printStackTrace();

        }finally {
            // 释放资源
            if (client != null) {
                try {
                    client.close();
                }catch (Exception e){

                }
            }


        }
        return null;
    }

    //通过url下载图片保存到本地


    static String getFile(String url,String fileName) {
        CloseableHttpClient client=null;
        HttpResponse response=null;
        try {
            client = HttpClientBuilder.create().build();
            HttpGet request = new HttpGet(url);


            response = client.execute(request);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String name = response.getFirstHeader("Content-Disposition").getValue();
                logger.info("==============file name :"+name);
                if(MyUtil.isNotEmpty(name)) {
                    String fn = name.replaceFirst("(?i)^.*filename=\"([^\"]+)\".*$", "$1");
                    if (MyUtil.isNotEmpty(fn)) {
                        logger.info("==============fn :" + fn);
                        int index = fn.lastIndexOf(".");
                        if (index > -1) {
                            String suffix = fn.substring(index);
                            fileName = fileName + suffix;
                        }
                    }
                }
                FileOutputStream fos = new FileOutputStream(fileName);
                entity.writeTo(fos);
                fos.close();
            }
            return  fileName;
        }catch (Exception e){
            e.printStackTrace();

        }finally {
            // 释放资源
            if (client != null) {
                try {
                    client.close();
                }catch (Exception e){

                }
            }


        }
        return null;
    }
    public static String getMedia(String token,String mediaId,String uploadPath){
        String url="http://api.weixin.qq.com/cgi-bin/media/get?access_token="+token+"&media_id="+mediaId;
        String fileName=null;
        try {
            fileName=downloadToDir(url, uploadPath);
        }catch (Exception e){
            e.printStackTrace();
            logger.info(e.toString());
            //logger.info(e.getStackTrace().toString());

        }
        return fileName;
    }



    public static String post(String url,String jsonString) {
        logger.info("url="+url);
        logger.info("post string="+jsonString);

        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        // 创建Post请求
        HttpPost httpPost = new HttpPost(url);

        // 我这里利用阿里的fastjson，将Object转换为json字符串;
        // (需要导入com.alibaba.fastjson.JSON包)
        //String jsonString = JSON.toJSONString(user);

        StringEntity entity = new StringEntity(jsonString, "UTF-8");

        // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
        httpPost.setEntity(entity);

        httpPost.setHeader("Content-Type", "application/json;charset=utf8");

        // 响应模型
        CloseableHttpResponse response = null;
        String ret=null;
        try {
            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();

            logger.info("响应状态为:" + response.getStatusLine());

            if (responseEntity != null) {

                ret=EntityUtils.toString(responseEntity,"utf-8");
                logger.info("响应内容为:" + ret);
            }
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            try {
                // 释放资源
                if (response != null) {
                    try {
                        response.close();
                    }catch (Exception e){

                    }
                }
                if (httpClient != null) {
                    try {
                        httpClient.close();
                    }catch (Exception e){

                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return ret;
    }


}
